<template>
  <div class="address-management">
    <el-table :data="orderList" stripe style="width: 100%">
      <el-table-column prop="productOrderCode" label="订单编号" />
      <el-table-column prop="productTitle" label="商品名称" />
      <el-table-column prop="productOrderReceiver" label="收货人" />
      <el-table-column prop="productOrderMobile" label="联系电话" />
      <el-table-column label="收货地址">
        <template #default="scope">
          {{ scope.row.productOrderDetailAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="productOrderTotalPrice" label="订单金额" />
      <el-table-column prop="productOrderPayDate" label="下单时间" />
      <el-table-column label="订单状态">
        <template #default="scope">
          <el-tag v-if="scope.row.productOrderStatus === '待付款'" type="info">待付款</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '待发货'" type="success">待发货</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '待确认'" type="warning">待确认</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '交易成功'" type="success">交易成功</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '交易关闭'" type="info">交易关闭</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '已发货'" type="primary">已发货</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '已确认'" type="success">已确认</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '退货中'" type="warning">退货中</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '退货成功'" type="info">退货成功</el-tag>
          <el-tag v-else-if="scope.row.productOrderStatus === '退货失败'" type="danger">退货失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px">
        <template #default="scope">
          <el-button v-if="scope.row.productOrderStatus === '待付款'" size="small" type="danger"
            @click="cancelOrder(scope.row)">
            取消订单
          </el-button>
          <el-button v-if="scope.row.productOrderStatus === '已发货'" size="small" type="primary"
            @click="confirmReceipt(scope.row)">
            确认收货
          </el-button>
          <el-button v-if="
            scope.row.productOrderStatus === '交易成功' ||
            scope.row.productOrderStatus === '待确认' ||
            scope.row.productOrderStatus === '已发货' ||
            scope.row.productOrderStatus === '待发货'
          " size="small" type="warning" @click="requestReturn(scope.row)">
            申请退货
          </el-button>
          <el-button size="small" @click="viewOrderDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="dialogVisible" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{
          currentOrder.productOrderCode
        }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{
          currentOrder.productOrderReceiver
        }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{
          currentOrder.productOrderMobile
        }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{
          currentOrder.productOrderDetailAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="邮政编码">{{
          currentOrder.productOrderPost
        }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">￥{{ currentOrder.productOrderTotalPrice }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{
          formatDate(currentOrder.productOrderPayDate)
        }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{
          currentOrder.productOrderStatus
        }}</el-descriptions-item>
        <el-descriptions-item label="买家留言">{{
          currentOrder.productOrderItems[0]?.productOrderItemUserMessage || "无"
        }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 退货申请对话框 -->
    <el-dialog v-model="dialogFormVisible" title="退货申请原因" width="500">
      <el-form :model="form">
        <el-form-item label="原因" >
            <el-select v-model="form.reason" placeholder="请选择退货原因">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="form.description"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReturn()">
            确认退货
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import instance from "@/utils/request";

// 订单列表
const orderList = ref([]);

// 对话框相关
const dialogVisible = ref(false);
const currentOrder = ref({});
const dialogFormVisible = ref(false)
// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN");
};
const options = ref([]);
const form = ref({
  productOrderCode: null,
  productTitle: '',
  reason: '',
  description:''

})
// 退货申请原因获取
const getReturnReasons = async () => {
  try {
    const response = await instance.get("/reason/userList");
    console.log(response.data)
    if (response.data.code === 200) {
      options.value = response.data.data.map(item => ({
        value: item.id,
        label: item.reason
      }));
    } else {
      ElMessage.error(response.data.message || "获取退货原因失败");
    }
  } catch (error) {
    console.error("获取退货原因出错:", error);
    ElMessage.error("获取退货原因失败");
  }
};
// 获取订单列表
const getOrderList = async () => {
  try {
    const response = await instance.get("/order/getPersonalOrder");

    if (response.data.code === 200) {
      orderList.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || "获取订单列表失败");
    }
  } catch (error) {
    console.error("获取订单列表出错:", error);
    ElMessage.error("获取订单列表失败");
  }
};

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order;
  dialogVisible.value = true;
};

// 取消订单
const cancelOrder = (order) => {
  console.log("取消订单", order);
  ElMessageBox.confirm(`确定要取消订单 ${order.productOrderCode} 吗？`, "确认取消", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const number = 4; // 假设取消订单后状态变为交易关闭
      try {
        const response = await instance.post("/order/updateOrderStatus", {
          productOrderCode: order.productOrderCode,
          productOrderStatus: number,
        });
        if (response.data.code === 200) {
          ElMessage.success("订单取消成功");
          getOrderList(); // 刷新订单列表
        } else {
          ElMessage.error(response.data.message || "取消订单失败");
        }
      } catch (error) {
        console.error("取消订单出错:", error);
        ElMessage.error("取消订单失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 确认收货
const confirmReceipt = (order) => {
  ElMessageBox.confirm(
    `确定已收到订单 ${order.productOrderCode} 的货物吗？`,
    "确认收货",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      const number = 6; // 假设确认收货后状态变为已完成
      try {
        const response = await instance.post("/order/updateOrderStatus", {
          productOrderCode: order.productOrderCode,
          productOrderStatus: number,
        });
        if (response.data.code === 200) {
          ElMessage.success("确认收货成功");
          getOrderList(); // 刷新订单列表
        } else {
          ElMessage.error(response.data.message || "确认收货失败");
        }
      } catch (error) {
        console.error("确认收货出错:", error);
        ElMessage.error("确认收货失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 申请退货
const requestReturn = (order) => {

  dialogFormVisible.value = true;
  form.value.productOrderCode = order.productOrderCode;
  form.value.productTitle = order.productTitle;
  console.log(order);

};
// 提交退货申请
const submitReturn = async () => {
  const number = 8; // 假设退货申请后状态变为退货中
  try {
    const response = await instance.post("/returnRecords/insert", {
      ...form.value
    });
    const res = await instance.post("/order/updateOrderStatus", {
      productOrderCode: form.value.productOrderCode,
      productOrderStatus: number
    });
    if (response.data.code === 200 && res.data.code === 200) {
      ElMessage.success("退货申请提交成功");
      dialogFormVisible.value = false;
      getOrderList(); // 刷新订单列表
    } else {
      ElMessage.error(response.data.message || "退货申请提交失败");
    }
  } catch (error) {
    console.error("退货申请提交出错:", error);
    ElMessage.error("退货申请提交失败");
  }
};

// 组件挂载时获取订单列表
onMounted(() => {
  getOrderList();
  getReturnReasons();
});
</script>

<style scoped>
.address-management {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
